var express = require("express");
var router = express.Router();
let jwt = require('jsonwebtoken')
var multiparty = require('multiparty')
var { Wang } = require("../model/model");
const {
  User,
  PeopleliveserveModel,
  MenuModel,
  RoleModel,
  wenModel,
  policiesAndRegulationsTypeModel,
  policiesAndRegulationsModel,
  specialEducationTypeModel,
  specialEducationModel,
  partymanagementModel,
  partymemberModel,
  leadingbodyModel,
  Birthdaymodel,
} = require("../model/model");
/* GET home page. */
router.get("/", function (req, res, next) {
  res.send({ title: "Express" });
});

//秘钥777
const secretKey = "secretKey";
//生成token
function gettoken(payload) {
  const dtoken =
    "Bearer " + jwt.sign(payload, secretKey, { expiresIn: 60 * 2 });
  const ctoken =
    "Bearer " + jwt.sign(payload, secretKey, { expiresIn: 60 * 60 * 24 });
  return { dtoken, ctoken };
}
router.get("/login", (req, res) => {
  res.send("请使用post请求");
});
router.post("/login", async (req, res) => {
  let { name, password } = req.body;
  let list = await User.findOne({ name }).populate("rid");
  if (list) {
    if (list.password == password) {
      let role = await RoleModel.findOne({ _id: list.rid._id })
        .populate("mid")
        .lean();
      let menu = role.mid;
      let obj = {}; //键是分类的_id 值是整个对象
      menu.forEach((item) => {
        obj[item._id] = item;
      });
      let data = [];
      menu.forEach((item) => {
        if (!item["mid"]) {
          data.push(item);
        } else {
          if (obj[item["mid"]] && !obj[item["mid"]]["children"]) {
            obj[item["mid"]]["children"] = [];
          }
          if (obj[item["mid"]]) {
            obj[item["mid"]]["children"].push(item);
          }
        }
      });

      const { ctoken, dtoken } = gettoken({ name });
      res.send({ ctoken, dtoken, code: 200, msg: "登录成功", menu: data });
    } else {
      res.send({ code: 403, msg: "密码错误" });
    }
  } else {
    res.send({ code: 403, msg: "用户名不存在" });
  }
});


router.post("/refresh", (req, res) => {
  let refreshToken = req.body.refreshToken;
  try {
    refreshToken = refreshToken.replace("Bearer ", "");
    const { name } = jwt.verify(refreshToken, secretKey);
    const accessToken = "Bearer " + jwt.sign({ name }, secretKey, { expiresIn: 60 });
    res.send({ accessToken });
  } catch (err) {

    res.send({ code: 403, msg: "登录失败" });
  }
});

//政策法规类型新增api
router.post('/policiesAndRegulationsTypeAdd', (req, res) => {
  let data = req.body

  policiesAndRegulationsTypeModel.create(data)
  res.send({ res: '添加成功', code: 200 })
})
//获取政策法规类型api
router.get("/policiesAndRegulationsTypeGet", (req, res) => {
  policiesAndRegulationsTypeModel.find().then((data) => {
    res.send({ res: "获取成功", data });
  });
});
// 删除政策法规类型api
router.delete('/policiesAndRegulationsTypeDel', async (req, res) => {
  let { id } = req.query

  await policiesAndRegulationsTypeModel.deleteOne({ _id: id })
    .then(() => {
      res.send({ res: '删除成功', code: 200 })
    })
})
// 修改政策法规api z指定字段修改isMyUrl type title author cover content visibleRange
router.post('/policiesAndRegulationsTypeUpdate', async (req, res) => {
  let { type, title, author, cover, content, visibleRange } = req.body
  let id = req.query.id
  console.log(req.body)
  console.log(id)
  await policiesAndRegulationsModel.updateOne({ _id: id }, { type, title, author, cover, content, visibleRange })
  res.send({ res: '修改成功', code: 200 })
});

// 政策法规新增api
router.post('/policiesAndRegulationsAdd', (req, res) => {
  let data = req.body

  policiesAndRegulationsModel.create(data)
  res.send({
    reg: '添加成功',
    code: 200
  })
})
// 政策法规获取加根据title模糊搜索type搜索 分页
router.get('/policiesAndRegulationsGet', async (req, res) => {
  let { title, type, page, pageSize } = req.query
  let data = await policiesAndRegulationsModel.find().populate('type')
  if (title) {
    data = data.filter((item) => item.title.includes(title));
  }
  if (type) {
    data = data.filter((item) => item.type.name == type);
  }
  let total = data.length
  console.log(total)
  data = data.slice((page - 1) * pageSize, page * pageSize)
  console.log(data)
  res.send({ res: '获取成功', data, total })
});

//政策法规是否置顶状态改变
router.post("/policiesAndRegulationsTop", async (req, res) => {
  let { id, top } = req.body;
  console.log(id, top);
  await policiesAndRegulationsModel.updateOne({ _id: id }, { isTop: top });
  res.send({ res: "修改成功" });
});
//政策法规是否轮播状态改变
router.post("/policiesAndRegulationsCarousel", async (req, res) => {
  let { id, Carousel } = req.body;
  console.log(id, Carousel);
  await policiesAndRegulationsModel.updateOne(
    { _id: id },
    { isCarousel: Carousel }
  );
  res.send({ res: "修改成功" });
});
//政策法规是否推荐状态改变
router.post('/policiesAndRegulationsRecommend', async (req, res) => {
  let { id, Recommend } = req.body
  console.log(id, Recommend)
  await policiesAndRegulationsModel.updateOne({ _id: id }, { isRecommend: Recommend })
  res.send({ res: '修改成功' })
})

//政策法规批量删除api

router.post('/policiesAndRegulationsDel', async (req, res) => {
  //批量删除根据数组中的id删除
  let { id } = req.body
  await policiesAndRegulationsModel.deleteMany({ _id: { $in: id } })
    .then(() => {
      res.send({ res: '删除成功', code: 200 })
    })
})
// 政策法规新增封面api
router.post('/newCoverForEducationImg', (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = 'upload/TextImg'
  form.parse(req, (err, formDate, imgDate) => {
    res.send({
      code: 201,
      data: imgDate.file[0].path,
    })
  })
  console.log(form, 113245)
})

// 专题教育获取类型api
router.get('/specialEducationTypeGet', (req, res) => {
  specialEducationTypeModel.find()
    .then((data) => {
      res.send({ res: '获取成功', data })
    })
})
// 专题教育新增类型api
router.post('/specialEducationTypeAdd', (req, res) => {
  let data = req.body

  specialEducationTypeModel.create(data)
  res.send({ res: '添加成功', code: 200 })
})
// 专题教育修改类型api
router.post('/specialEducationTypeUpdate', async (req, res) => {
  let { id, name } = req.body

  await specialEducationTypeModel.updateOne({ _id: id }, { name })
    .then(() => {
      res.send({ res: '修改成功', code: 200 })
    })
})
// 专题教育删除类型api
router.post('/specialEducationTypeDel', async (req, res) => {
  let { id } = req.query

  await specialEducationTypeModel.deleteOne({ _id: id })
    .then(() => {
      res.send({ res: '删除成功', code: 200 })
    })
})
//专题教育 获取加根据title模糊搜索type搜索
router.get('/specialEducationGet', async (req, res) => {
  let { title, type, page, pageSize } = req.query
  let data = await specialEducationModel.find().populate('type')

  if (title) {
    data = data.filter(item => item.title.includes(title))
  }
  if (type) {
    data = data.filter(item => item.type.name == type)
  }
  let total = data.length
  console.log(total)
  data = data.slice((page - 1) * pageSize, page * pageSize)
  console.log(data)
  res.send({ res: '获取成功', data, total })
})
//专题教育是否置顶状态改变
router.post('/specialEducationTop', async (req, res) => {
  let { id, top } = req.body
  console.log(id, top)
  await specialEducationModel.updateOne({ _id: id }, { isTop: top })
  res.send({
    code: 200,
    msg: '修改成功'
  })
})
//专题教育是否轮播状态改变
router.post('/specialEducationCarousel', async (req, res) => {
  let { id, Carousel } = req.body
  console.log(id, Carousel)
  await specialEducationModel.updateOne({ _id: id }, { isCarousel: Carousel })
  res.send({ res: '修改成功' })
})
//专题教育是否推荐状态改变
router.post('/specialEducationRecommend', async (req, res) => {
  let { id, Recommend } = req.body
  console.log(id, Recommend)
  await specialEducationModel.updateOne({ _id: id }, { isRecommend: Recommend })
  res.send({ res: '修改成功' })
})

// 专题教育添加api
router.post('/specialEducationAdd', (req, res) => {
  let data = req.body
  specialEducationModel.create(data)
    .then(() => {
      res.send({ res: '添加成功', code: 200 })
    }
    )
})

// 修改专题教育api z指定字段修改isMyUrl type title author cover content visibleRange
router.post('/specialEducationUpdate', async (req, res) => {
  let { type, title, author, cover, content, visibleRange } = req.body
  let id = req.query.id
  console.log(req.body)
  console.log(id)
  await specialEducationModel.updateOne({ _id: id }, { type, title, author, cover, content, visibleRange })
  res.send({ res: '修改成功', code: 200 })
});

//专题批量删除api
router.post('/specialEducationDel', async (req, res) => {
  //批量删除根据数组中的id删除
  let { id } = req.body
  await specialEducationModel.deleteMany({ _id: { $in: id } })
    .then(() => {
      res.send({ res: '删除成功', code: 200 })
    })
})
router.get("/Peopleliveserve", async (req, res) => {
  let {
    driction,
    type,
    status,
    people,
    phone,
    address,
    inter,
    process,
    cpeople,
  } = req.query;

  let list = await PeopleliveserveModel.find();
  if (driction) {
    list = list.filter((item) => item.driction == driction);
  }
  if (type) {
    list = list.filter((item) => item.type == type);
  }
  if (status) {
    list = list.filter((item) => item.status == status);
  }
  if (people) {
    list = list.filter((item) => item.people == people);
  }
  if (phone) {
    list = list.filter((item) => item.phone == phone);
  }
  if (address) {
    list = list.filter((item) => item.address == address);
  }
  if (inter) {
    list = list.filter((item) => item.inter == inter);
  }
  if (process) {
    list = list.filter((item) => item.process == process);
  }
  if (cpeople) {
    list = list.filter((item) => item.cpeople == cpeople);
  }
  res.send({ list, code: 200 });
});

//菜单权限
router.get("/menu", async (req, res) => {
  list = await MenuModel.find().lean();
  let obj = {}; //键是分类的_id 值是整个对象
  list.forEach((item) => {
    obj[item._id] = item;
  });
  let data = [];

  list.forEach((item) => {
    if (!item["mid"]) {
      data.push(item);
    } else {
      if (obj[item["mid"]] && !obj[item["mid"]]["children"]) {
        obj[item["mid"]]["children"] = [];
      }
      if (obj[item["mid"]]) {
        obj[item["mid"]]["children"].push(item);
      }
    }
  });
  res.send({ data, code: 200 });
});
router.get("/role", async (req, res) => {
  let list = await RoleModel.find().populate("mid");

  res.send({ list, code: 200 });
});

// 网格管理
router.get("/wang", async (req, res) => {
  const data = await Wang.find();
  res.send({ data, code: 200, msg: "成功" });
});

//智慧党建 组织管理  党组织管理

router.get("/zjgl", async (req, res) => {
  let { name } = req.query;

  let list = [];
  list = await partymanagementModel.find();
  if (name) {
    list = list.filter((item) => item.name.includes(name));
  }
  res.send({
    list,
  });
});

//智慧党建 组织管理  党组织管理  新增
router.post("/zjgladd", (req, res) => {
  partymanagementModel.create(req.body);
  res.send({ code: 200, msg: "添加成功" });
});

//智慧党建 组织管理  党组织管理  删除
router.delete("/zjgldel", async (req, res) => {
  let { id } = req.query;
  await partymanagementModel.deleteOne({ _id: id });
  res.send({ code: 210, msg: "删除成功" });
});

//智慧党建 组织管理  党组织管理  编辑
router.put("/zjglupdate", async (req, res) => {
  let body = req.body;
  let id = body.id;
  await partymanagementModel.updateOne({ _id: id }, body);
  res.send({ code: 220, msg: "编辑成功" });
});

//智慧党建 组织管理  领导班子
router.get("/ldbz", async (req, res) => {
  let { name, page, limit } = req.query;

  //分页
  let skip = (page - 1) * limit; //跳过多少条
  let count = await leadingbodyModel.find().count(); //总条数
  let pages = Math.ceil(count / limit); //总页数

  let list = await leadingbodyModel.find().skip(skip).limit(limit); //分页数据
  if (name) {
    list = list.filter((item) => item.name.includes(name));
  }
  res.send({
    list,
    pages,
    count,
    skip,
  });
});

//智慧党建 组织管理  领导班子  新增
router.post("/ldbzadd", (req, res) => {
  leadingbodyModel.create(req.body);
  res.send({ code: 230, msg: "添加成功" });
});

//智慧党建 组织管理  领导班子  删除
router.delete("/ldbzdel", async (req, res) => {
  let { id } = req.query;
  await leadingbodyModel.deleteOne({ _id: id });
  res.send({ code: 231, msg: "删除成功" });
});

//智慧党建 组织管理  领导班子  编辑
router.put("/ldbzupdate", async (req, res) => {
  let body = req.body;
  let id = body.id;
  await leadingbodyModel.updateOne({ _id: id }, body);
  res.send({ code: 232, msg: "编辑成功" });
});
//智慧党建 组织管理  党员管理
router.get("/dygl", async (req, res) => {
  let { name, organization } = req.query;
  let list = [];
  let typelist = [];
  list = await partymemberModel.find();
  typelist = await partymemberModel.find().distinct("organization");
  if (name) {
    list = list.filter((item) => item.name.includes(name));
  }
  if (organization) {
    list = list.filter((item) => item.organization.includes(organization));
  }
  res.send({
    list,
    typelist,
  });
});
//智慧党建 组织管理  党员管理  新增
router.post("/dygladd", (req, res) => {
  partymemberModel.create(req.body);
  res.send({ code: 240, msg: "添加成功" });
});
//智慧党建 组织管理  党员管理  删除
router.delete("/dygldel", async (req, res) => {
  let { id } = req.query;
  await partymemberModel.deleteOne({ _id: id });
  res.send({ code: 241, msg: "删除成功" });
});
//智慧党建 组织管理  党员管理  编辑
router.put("/dyglupdate", async (req, res) => {
  let body = req.body;
  let id = body._id;
  await partymemberModel.updateOne({ _id: id }, body);
  res.send({ code: 242, msg: "编辑成功" });
});

//智慧党建 组织管理  党员管理  批量删除
router.delete("/dygldels", async (req, res) => {
  let { ids } = req.query;
  let idarr = ids.split(",");

  await partymemberModel.deleteMany({ _id: { $in: idarr } });
  res.send({ code: 243, msg: "批量删除成功" });
});

// 请求数据birthday
router.get("/birthdayshow", async (req, res) => {
  let list = await Birthdaymodel.find();
  res.send({ list, code: 200 });
});
// 模糊搜索接口birthday
router.get("/birthdaysearch", async (req, res) => {
  let { name } = req.query;
  let list = await Birthdaymodel.find({ name: { $regex: name } });
  res.send({ list, code: 200 });
});
// birthday添加接口
router.post("/birthdayadd", async (req, res) => {
  let { data } = req.body;
  await Birthdaymodel.create(data);
  res.send({ msg: "添加成功" });
});
//防止失败
router.get("/user", async (req, res) => {
  res.send({ msg: "哈哈哈，别搞我" });
});
router.get("/upload", async (req, res) => {
  res.send({ msg: "哈哈哈，别搞我" });
});
//获取所有权限
router.get("/getmenu", async (req, res) => {
  let list = await MenuModel.find().lean();
  let obj = {}
  list.forEach(item => {
    obj[item._id] = item
  })
  let menu = []
  list.forEach(item => {
    if (!item.mid) {
      menu.push(item)
    } else {
      if (item['mid'] && !obj[item.mid].children) { obj[item.mid].children = [] }
      if (item['mid']) { obj[item.mid].children.push(item) }

    }
  })
  res.send({ msg: '成功', code: 200, data: menu });
})
module.exports = router;
